package com.example.demoapp.common;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.example.demoapp.entity.Employee;
import com.example.demoapp.exception.BusinessException;
import com.example.demoapp.service.EmployeeService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;


//拦截器
@Component
public class JwtInterceptor implements HandlerInterceptor {
    //引入员工表的service资源
    @Resource
    private EmployeeService employeeService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String  token = request.getHeader("token");
        //校验token
        if(StrUtil.isBlank(token)){
            //尝试从参数获取token（适配导出类的请求，请求头没有token可能会放在参数）
            token = request.getParameter("token");
        }
        //验证token是否存在
        if(StrUtil.isBlank(token)){
            throw new BusinessException(401,"您无权操作(token不存在)");
        }

        Employee employee = null;

        try{
            //在try内 以下的步骤有错直接就抛出错误（说明token校验失败了）
            //拿到token的负载（存有userid和role） decode（解码） getAudience获取解码后的负载 get(0)获取第一项（信息） 第二项为密码
            String audience = JWT.decode(token).getAudience().get(0);
            String [] split = audience.split("-");
            Integer userId = Integer.valueOf(split[0]);
            String role = split[1];

            //根据id去查询是否有这个账号
            employee =  employeeService.selecByid(userId);

        } catch (Exception e) {
            System.out.println(e.getMessage());
            throw new BusinessException(401,"您无权操作(账号查询失败)");
        }

        if(employee == null){
            throw new BusinessException(401,"您无权操作(账号查询失败2)");
        }

        try{
            //加签器 验证签名
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(employee.getPassword())).build();
            jwtVerifier.verify(token);
        } catch (Exception e) {
            System.out.println(employee);
            throw new BusinessException(401,"您无权操作（token验证失败）");
        }

        return true;
    }
}
